/*
 * @Author: 陈德基
 * @Date: 2021-11-15 18:06:21
 * @LastEditTime: 2021-11-16 19:42:57
 * @Description: 
 * @FilePath: \copy_gsy_github_app_flutter\lib\db\provider\user\userinfo_db_provider.dart
 * 联系方式：
 * wx: melody_2009
 * qq: 7815171323 
 */

import 'package:copy_gsy_github_app_flutter/common/model/User.dart';
import 'package:copy_gsy_github_app_flutter/db/sql_provider.dart';
import 'package:copy_gsy_github_app_flutter/utils/code_utils.dart';
import 'package:flutter/foundation.dart';
import 'package:sqflite/sqlite_api.dart';

class UserInfoDBProvider extends DBProvider {
  static const NAME = 'UserInfo';
  static const COLUMN_ID = '_id';
  static const COLUMN_USERNAME = 'userName';
  static const COLUMN_DATA = 'data';

  int? id;
  String? userName;
  String? data;

  UserInfoDBProvider();

  Map<String, dynamic> toMap(String userName, String data) {
    Map<String, dynamic> map = {COLUMN_USERNAME: userName, COLUMN_DATA: data};
    if (id != null) {
      map[COLUMN_ID] = id;
    }
    return map;
  }

  UserInfoDBProvider.fromMap(Map map) {
    id = map[COLUMN_ID];
    userName = map[COLUMN_USERNAME];
    data = map[COLUMN_DATA];
  }

  @override
  sqlCreateTable() {
    return tableBaseString(NAME, COLUMN_ID) +
        '''
        $COLUMN_USERNAME text not null,
        $COLUMN_DATA text not null)
      ''';
  }

  @override
  tableName() {
    return NAME;
  }

  _getUserProvider(Database db, String? userName) async {
    List<Map<String, dynamic>> maps = await db.query(NAME,
        columns: [COLUMN_ID, COLUMN_USERNAME, COLUMN_DATA],
        where: '$COLUMN_USERNAME = ?',
        whereArgs: [userName]);
    if (maps.length > 0) {
      UserInfoDBProvider provider = UserInfoDBProvider.fromMap(maps.first);
      return provider;
    }
    return null;
  }

  insert(String userName, String mapString) async {
    Database db = await getDataBase();
    var userProvider = await _getUserProvider(db, userName);
    if (userProvider != null) {
      // 存在直接更新
      await db.update(NAME, toMap(userName, mapString),
          where: '$COLUMN_USERNAME = ?', whereArgs: [userName]);
    } else {
      // 不存在插入
      await db.insert(NAME, toMap(userName, mapString));
    }
  }

  getUserInfo(String userName) async {
    Database db = await getDataBase();
    var provider = await _getUserProvider(db, userName);
    if (provider != null) {
      var mapData =
          await compute(CodeUtils.decodeMapResult, provider.data as String);
      return User.fromJson(mapData);
    }
    return null;
  }
}
